import React, { useState, useEffect } from 'react';
import type { Employee } from '../types';
import { generateJobDescriptionStream } from '../services/geminiService';
import { SparkleIcon } from './icons/SparkleIcon';

interface EmployeeModalProps {
  employee: Employee | null;
  onClose: () => void;
  onSave: (employee: Omit<Employee, 'id' | 'avatar'> & { id?: number }) => void;
}

const EmployeeModal: React.FC<EmployeeModalProps> = ({ employee, onClose, onSave }) => {
  const [formData, setFormData] = useState<Partial<Employee>>({
    name: '',
    email: '',
    position: '',
    department: '',
    hireDate: '',
    salary: 0,
    jobDescription: '',
  });
  const [isGenerating, setIsGenerating] = useState(false);

  useEffect(() => {
    if (employee) {
      setFormData(employee);
    } else {
      setFormData({
        name: '',
        email: '',
        position: '',
        department: '',
        hireDate: new Date().toISOString().split('T')[0],
        salary: 10000,
        jobDescription: '',
      });
    }
  }, [employee]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: name === 'salary' ? parseInt(value) : value }));
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    // We cast here, but parent component expects a version that might not have id/avatar
    onSave(formData as Omit<Employee, 'id' | 'avatar'> & { id?: number });
  };
  
  const handleGenerateDescription = async () => {
    if (!formData.position) {
      alert("请先输入职位名称。");
      return;
    }
    setIsGenerating(true);
    setFormData(prev => ({...prev, jobDescription: ''}));
    
    await generateJobDescriptionStream(formData.position, (chunk) => {
        setFormData(prev => ({
            ...prev,
            jobDescription: (prev.jobDescription || '') + chunk
        }));
    });

    setIsGenerating(false);
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex justify-center items-center z-50 transition-opacity">
      <div className="bg-white rounded-xl shadow-2xl p-8 w-full max-w-2xl transform transition-transform scale-100">
        <div className="flex justify-between items-center mb-6">
          <h2 className="text-2xl font-bold text-slate-800">{employee ? '编辑员工信息' : '添加新员工'}</h2>
          <button onClick={onClose} className="text-slate-400 hover:text-slate-600">
            <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" /></svg>
          </button>
        </div>
        <form onSubmit={handleSubmit}>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label className="block text-sm font-medium text-slate-700">姓名</label>
              <input type="text" name="name" value={formData.name} onChange={handleChange} className="mt-1 block w-full px-3 py-2 bg-white border border-slate-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" required />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700">电子邮箱</label>
              <input type="email" name="email" value={formData.email} onChange={handleChange} className="mt-1 block w-full px-3 py-2 bg-white border border-slate-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" required />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700">职位</label>
              <input type="text" name="position" value={formData.position} onChange={handleChange} className="mt-1 block w-full px-3 py-2 bg-white border border-slate-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" required />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700">部门</label>
              <input type="text" name="department" value={formData.department} onChange={handleChange} className="mt-1 block w-full px-3 py-2 bg-white border border-slate-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" required />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700">入职日期</label>
              <input type="date" name="hireDate" value={formData.hireDate} onChange={handleChange} className="mt-1 block w-full px-3 py-2 bg-white border border-slate-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" required />
            </div>
             <div>
              <label className="block text-sm font-medium text-slate-700">月薪</label>
              <input type="number" name="salary" value={formData.salary} onChange={handleChange} className="mt-1 block w-full px-3 py-2 bg-white border border-slate-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500" required />
            </div>
            <div className="md:col-span-2">
                <div className="flex justify-between items-center mb-1">
                    <label className="block text-sm font-medium text-slate-700">职位描述</label>
                    <button type="button" onClick={handleGenerateDescription} disabled={isGenerating} className="flex items-center text-xs text-indigo-600 hover:text-indigo-800 disabled:opacity-50 disabled:cursor-not-allowed">
                        <SparkleIcon />
                        <span className="ml-1">{isGenerating ? '生成中...' : 'AI 生成'}</span>
                    </button>
                </div>
              <textarea name="jobDescription" value={formData.jobDescription} onChange={handleChange} rows={5} className="mt-1 block w-full px-3 py-2 bg-white border border-slate-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"></textarea>
            </div>
          </div>
          <div className="mt-8 flex justify-end space-x-3">
            <button type="button" onClick={onClose} className="px-4 py-2 bg-slate-200 text-slate-800 rounded-lg hover:bg-slate-300">取消</button>
            <button type="submit" className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700">保存</button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default EmployeeModal;